<template>
    <div class="image-editor">
      <!-- 图片上传 -->
      <input type="file" accept="image/*" @change="handleFileChange" />
      
      <!-- 图片预览 -->
      <div v-if="imageUrl">
        <canvas ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
        <div class="controls">
          <button @click="rotateImage">旋转图片</button>
          <button @click="cropImage">裁剪图片</button>
          <button @click="resetImage">重置</button>
          <button @click="saveImage">保存编辑</button>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        imageUrl: null, // 存储图片URL
        originalImage: null, // 存储原始图片数据
        rotation: 0, // 当前图片的旋转角度
        canvasWidth: 500, // Canvas宽度
        canvasHeight: 500, // Canvas高度
      };
    },
    methods: {
      // 处理文件选择
      handleFileChange(event) {
        const file = event.target.files[0];
        if (file) {
          this.imageUrl = URL.createObjectURL(file);
          this.loadImage(file);
        }
      },
      // 加载图片到canvas
      loadImage(file) {
        const img = new Image();
        img.src = URL.createObjectURL(file);
        img.onload = () => {
          this.originalImage = img;
          this.drawImage();
        };
      },
      // 绘制图片到canvas
      drawImage() {
        const ctx = this.$refs.canvas.getContext("2d");
        ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); // 清除之前的绘制
        ctx.save(); // 保存当前状态
        ctx.translate(this.canvasWidth / 2, this.canvasHeight / 2); // 设置旋转中心点
        ctx.rotate((this.rotation * Math.PI) / 180); // 应用旋转
        ctx.drawImage(this.originalImage, -this.originalImage.width / 2, -this.originalImage.height / 2);
        ctx.restore(); // 恢复状态
      },
      // 旋转图片
      rotateImage() {
        this.rotation += 90; // 每次点击旋转90度
        this.drawImage();
      },
      // 裁剪图片
      cropImage() {
        const ctx = this.$refs.canvas.getContext("2d");
        const imageData = ctx.getImageData(50, 50, 200, 200); // 假设裁剪一个 200x200 的区域
        ctx.putImageData(imageData, 0, 0); // 将裁剪的区域放置到画布的顶部
      },
      // 重置图片
      resetImage() {
        this.rotation = 0;
        this.drawImage();
      },
      // 保存编辑后的图片并上传到服务器
      saveImage() {
        const canvas = this.$refs.canvas;
        const dataUrl = canvas.toDataURL("image/png"); // 获取编辑后的图片的Data URL
        this.uploadImage(dataUrl); // 上传编辑后的图片
      },
      // 上传图片到服务器
      async uploadImage(dataUrl) {
        // 生成一个 FormData 对象
        const formData = new FormData();
        // 转换 Data URL 为 Blob 对象
        const byteString = atob(dataUrl.split(",")[1]);
        const arrayBuffer = new ArrayBuffer(byteString.length);
        const uintArray = new Uint8Array(arrayBuffer);
        for (let i = 0; i < byteString.length; i++) {
          uintArray[i] = byteString.charCodeAt(i);
        }
        const blob = new Blob([arrayBuffer], { type: "image/png" });
        formData.append("image", blob, "edited_image.png");
  
        try {
          const response = await fetch("http://localhost:3000/upload", {
            method: "POST",
            body: formData,
          });
  
          if (!response.ok) {
            throw new Error("Failed to upload image");
          }
  
          const data = await response.json();
          if (data.success) {
            alert("图片已保存并覆盖原图！");
          } else {
            alert("图片保存失败！");
          }
        } catch (error) {
          console.error("Error uploading image:", error);
          alert("上传失败！");
        }
      },
    },
  };
  </script>
  
  <style scoped>
  .image-editor {
    text-align: center;
    margin-top: 20px;
  }
  
  canvas {
    border: 1px solid #ccc;
  }
  
  .controls {
    margin-top: 10px;
  }
  
  button {
    margin: 5px;
  }
  </style>
  